<template>
  <div class="form-container">
    <div class="form-header">
      <h2>创建新车辆</h2>
      <p>请填写以下信息创建新的车辆记录</p>
    </div>
    <el-form
      :model="formData"
      ref="formDataRef"
      :rules="formRules"
      label-width="120px"
      class="car-form"
    >
      <!-- 使用可折叠面板组织表单内容 -->
      <el-collapse v-model="activeCollapse" accordion>
        <!-- 基本信息部分 -->
        <el-collapse-item title="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆品牌" prop="brand">
                <el-input v-model="formData.brand" placeholder="请输入品牌" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆型号" prop="model">
                <el-input v-model="formData.model" placeholder="请输入型号" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车辆级别" prop="level">
                <el-select
                  v-model="formData.level"
                  placeholder="请选择级别"
                  style="width: 100%"
                >
                  <el-option label="经济型" value="经济型" />
                  <el-option label="舒适型" value="舒适型" />
                  <el-option label="豪华型" value="豪华型" />
                  <el-option label="商务型" value="商务型" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="车辆类型" prop="type">
                <el-select
                  v-model="formData.type"
                  placeholder="请选择类型"
                  style="width: 100%"
                >
                  <el-option label="轿车" value="轿车" />
                  <el-option label="SUV" value="SUV" />
                  <el-option label="MPV" value="MPV" />
                  <el-option label="跑车" value="跑车" />
                  <el-option label="面包车" value="面包车" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="日租金" prop="dailyRate">
            <el-input-number
              v-model="formData.dailyRate"
              :min="0"
              :precision="2"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="车辆描述" prop="description">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入车辆描述信息"
            />
          </el-form-item>
        </el-collapse-item>

        <!-- 位置信息部分 -->
        <el-collapse-item title="位置信息" name="location">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="取车城市" prop="city">
                <el-input v-model="formData.city" placeholder="请输入城市" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="具体地址" prop="location">
                <el-input
                  v-model="formData.location"
                  placeholder="请输入详细地址"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="还车城市" prop="returnCities">
            <el-select
              v-model="formData.returnCities"
              multiple
              collapse-tags
              collapse-tags-tooltip
              placeholder="请选择还车城市"
              style="width: 100%"
            >
              <el-option
                v-for="item in cityOptions"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-collapse-item>

        <!-- 车辆规格部分 -->
        <el-collapse-item title="车辆规格" name="specifications">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="座位数" prop="specifications.seats">
                <el-input-number
                  v-model="formData.specifications.seats"
                  :min="1"
                  :max="20"
                  :precision="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="动力类型" prop="specifications.powerType">
                <el-select
                  v-model="formData.specifications.powerType"
                  placeholder="请选择动力类型"
                  style="width: 100%"
                >
                  <el-option label="燃油" value="燃油" />
                  <el-option label="纯电动" value="纯电动" />
                  <el-option label="混动" value="混动" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item
                label="油耗(L/100km)"
                prop="specifications.fuelConsumption"
              >
                <el-input-number
                  v-model="formData.specifications.fuelConsumption"
                  :min="0"
                  :precision="1"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="车长(mm)" prop="specifications.length">
                <el-input-number
                  v-model="formData.specifications.length"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车宽(mm)" prop="specifications.width">
                <el-input-number
                  v-model="formData.specifications.width"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="车高(mm)" prop="specifications.height">
                <el-input-number
                  v-model="formData.specifications.height"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item
                label="后备箱容积(L)"
                prop="specifications.trunkCapacity"
              >
                <el-input-number
                  v-model="formData.specifications.trunkCapacity"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col
              :span="12"
              v-if="formData.specifications.powerType === '纯电动'"
            >
              <el-form-item label="续航里程(km)" prop="specifications.range">
                <el-input-number
                  v-model="formData.specifications.range"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
        </el-collapse-item>

        <!-- 车辆图片部分 -->
        <el-collapse-item title="车辆图片" name="images">
          <el-form-item label="封面图片" prop="coverImage" class="upload-item">
            <el-upload
              class="avatar-uploader"
              action="#"
              :http-request="uploadCoverImage"
              :show-file-list="false"
              :before-upload="beforeImageUpload"
            >
              <img
                v-if="coverImageUrl"
                :src="coverImageUrl"
                class="cover-image"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">请上传车辆封面图片（必填）</div>
          </el-form-item>

          <el-form-item label="车辆图片" prop="images" class="upload-item">
            <el-upload
              v-model:file-list="fileList"
              class="upload-demo"
              action="#"
              :http-request="uploadCarImages"
              list-type="picture-card"
              :limit="10"
              :before-upload="beforeImageUpload"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
            <div class="upload-tip">可上传多张车辆图片（最多10张）</div>
          </el-form-item>
        </el-collapse-item>

        <!-- 附加服务部分 -->
        <el-collapse-item title="附加服务" name="services">
          <el-form-item label="附加服务">
            <div class="services-container">
              <div
                v-for="(service, index) in formData.additionalServices"
                :key="index"
                class="service-item"
              >
                <el-row :gutter="10">
                  <el-col :span="8">
                    <el-input v-model="service.name" placeholder="服务名称" />
                  </el-col>
                  <el-col :span="6">
                    <el-input-number
                      v-model="service.price"
                      :min="0"
                      :precision="2"
                      placeholder="价格"
                      style="width: 100%"
                    />
                  </el-col>
                  <el-col :span="8">
                    <el-input
                      v-model="service.description"
                      placeholder="服务描述"
                    />
                  </el-col>
                  <el-col :span="2">
                    <el-button
                      type="danger"
                      icon="Delete"
                      circle
                      @click="removeService(index)"
                    />
                  </el-col>
                </el-row>
              </div>
              <el-button type="primary" icon="Plus" @click="addService"
                >添加服务</el-button
              >
            </div>
          </el-form-item>
        </el-collapse-item>
      </el-collapse>

      <div class="form-actions">
        <el-button type="primary" @click="submitForm" :loading="submitting"
          >创建车辆</el-button
        >
        <el-button @click="resetForm">重置</el-button>
      </div>
    </el-form>
  </div>
</template>
  
<script setup>
import { reactive, ref, computed } from "vue";
import { messageSuccess, messageError } from "@/action/MessagePrompt";
import { Plus, Delete } from "@element-plus/icons-vue";
import carsApi from "@/http/cars.js";

// 控制折叠面板展开状态
const activeCollapse = ref(["basic"]);

// 表单数据
const formData = reactive({
  brand: "",
  model: "",
  level: "",
  type: "",
  dailyRate: 0,
  city: "",
  returnCities: [],
  location: "",
  description: "",
  coverImage: null,
  images: [],
  specifications: {
    seats: 5,
    powerType: "燃油",
    length: 0,
    width: 0,
    height: 0,
    trunkCapacity: 0,
    fuelConsumption: 0,
    range: 0,
  },
  additionalServices: [],
});

// 城市选项
const cityOptions = ref([
  "北京",
  "上海",
  "广州",
  "深圳",
  "杭州",
  "南京",
  "成都",
  "重庆",
  "武汉",
  "西安",
  "天津",
  "苏州",
  "长沙",
  "青岛",
  "大连",
]);

// 表单校验规则
const formRules = {
  brand: [{ required: true, message: "请输入车辆品牌", trigger: "blur" }],
  model: [{ required: true, message: "请输入车辆型号", trigger: "blur" }],
  level: [{ required: true, message: "请选择车辆级别", trigger: "change" }],
  type: [{ required: true, message: "请选择车辆类型", trigger: "change" }],
  dailyRate: [{ required: true, message: "请输入日租金", trigger: "blur" }],
  city: [{ required: true, message: "请输入取车城市", trigger: "blur" }],
  returnCities: [
    { required: true, message: "请选择至少一个还车城市", trigger: "change" },
  ],
  location: [{ required: true, message: "请输入具体地址", trigger: "blur" }],
  coverImage: [
    { required: true, message: "请上传封面图片", trigger: "change" },
  ],
  "specifications.seats": [
    { required: true, message: "请输入座位数", trigger: "blur" },
  ],
  "specifications.powerType": [
    { required: true, message: "请选择动力类型", trigger: "change" },
  ],
};

const formDataRef = ref(null);
const fileList = ref([]);
const coverImageUrl = ref("");
const submitting = ref(false);

// 图片上传前检查
const beforeImageUpload = (file) => {
  const isImage = file.type.startsWith("image/");
  const isLt5M = file.size / 1024 / 1024 < 5;

  if (!isImage) {
    messageError("只能上传图片文件!");
    return false;
  }
  if (!isLt5M) {
    messageError("图片大小不能超过 5MB!");
    return false;
  }
  return true;
};

// 上传封面图片
const uploadCoverImage = (options) => {
  formData.coverImage = options.file;
  // 预览封面图
  const reader = new FileReader();
  reader.onload = (e) => {
    coverImageUrl.value = e.target.result;
  };
  reader.readAsDataURL(options.file);
};

// 上传车辆图片
const uploadCarImages = (options) => {
  formData.images.push(options.file);
};

// 添加新服务
const addService = () => {
  formData.additionalServices.push({
    name: "",
    price: 0,
    description: "",
  });
};

// 移除服务
const removeService = (index) => {
  formData.additionalServices.splice(index, 1);
};

// 提交表单
const submitForm = async () => {
  if (!formDataRef.value) return;

  formDataRef.value.validate(async (valid) => {
    if (valid) {
      submitting.value = true;

      try {
        // 构建FormData
        const formDataToSend = new FormData();

        // 添加基本信息
        formDataToSend.append("brand", formData.brand);
        formDataToSend.append("model", formData.model);
        formDataToSend.append("level", formData.level);
        formDataToSend.append("type", formData.type);
        formDataToSend.append("dailyRate", formData.dailyRate);
        formDataToSend.append("city", formData.city);
        formData.returnCities.forEach((city) => {
          formDataToSend.append("returnCities", city);
        });
        formDataToSend.append("location", formData.location);

        // 添加描述（可选）
        if (formData.description) {
          formDataToSend.append("description", formData.description);
        }

        // 添加图片
        formDataToSend.append("coverImage", formData.coverImage);
        formData.images.forEach((image) => {
          formDataToSend.append("images", image);
        });

        // 添加规格信息
        Object.entries(formData.specifications).forEach(([key, value]) => {
          if (value || value === 0) {
            formDataToSend.append(`specifications.${key}`, value);
          }
        });

        // 添加附加服务（可选）
        if (formData.additionalServices.length > 0) {
          formDataToSend.append(
            "additionalServices",
            JSON.stringify(formData.additionalServices)
          );
        }

        // 发送请求
        const response = await carsApi.createCar(formDataToSend);

        if (response.success) {
          messageSuccess("车辆创建成功");
          resetForm();
        } else {
          messageError(response.message || "创建失败");
        }
      } catch (error) {
        console.error("创建车辆出错:", error);
        messageError(error.message || "创建失败");
      } finally {
        submitting.value = false;
      }
    } else {
      messageError("请填写所有必填项");
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  formDataRef.value?.resetFields();
  fileList.value = [];
  coverImageUrl.value = "";
  formData.coverImage = null;
  formData.images = [];
  formData.additionalServices = [];
  formData.specifications = {
    seats: 5,
    powerType: "燃油",
    length: 0,
    width: 0,
    height: 0,
    trunkCapacity: 0,
    fuelConsumption: 0,
    range: 0,
  };
};
</script>
  
<style lang="scss" scoped>
.form-container {
  max-width: 900px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ebeef5;
  border-radius: 8px;
  background-color: #fff;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  height: calc(100vh - 90px);
  overflow-y: auto;
  overflow-x: hidden;
}

.form-header {
  text-align: center;
  margin-bottom: 20px;

  h2 {
    font-size: 24px;
    color: #303133;
    margin-bottom: 10px;
  }

  p {
    color: #606266;
    font-size: 14px;
  }
}

.car-form {
  .el-form-item {
    margin-bottom: 15px;
  }
}

.upload-item {
  margin-bottom: 15px;
}

.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: center;

  .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: #409eff;
    }
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.cover-image {
  width: 178px;
  height: 178px;
  object-fit: cover;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 5px;
}

.services-container {
  .service-item {
    margin-bottom: 10px;
    padding: 10px;
    border: 1px dashed #e0e0e0;
    border-radius: 4px;
  }
}

:deep(.el-upload--picture-card) {
  --el-upload-picture-card-size: 120px;
}

:deep(.el-date-editor.el-input),
:deep(.el-date-editor.el-input__wrapper) {
  width: 100%;
}

.form-actions {
  margin-top: 20px;
  text-align: center;
}

:deep(.el-collapse-item__header) {
  font-weight: bold;
  font-size: 16px;
  background-color: #f5f7fa;
}

:deep(.el-collapse-item__content) {
  padding: 15px;
}

@media (max-width: 768px) {
  .form-container {
    padding: 15px;
    height: calc(100vh - 60px);
  }
}
</style>
  